﻿
--drop function must with save attribute
drop function AddressSave(out xml, inout xml);

create or replace function AddressSave(
  out xml, inout xml
)  as
$$
  declare
    statusXmlData  alias for $1;
    addressXmlData alias for $2;
    vIdAddress integer := null;
    vNameAddress text := null;
    vIdNode varchar(100) := '/address/@id';
    vNameAddressNode varchar(100) := '/address/addressName';
  begin
    vIdAddress := cast(extract_value(vIdNode, cast(addressXmlData as xml)) as integer);
    vNameAddress := extract_value(vNameAddressNode, cast(addressXmlData as xml));
    if (vIdAddress = null or vIdAddress = noId()) then begin
		insert into addressTable(nameAddress) values(vNameAddress) returning idaddress into vIdAddress;
		addressXmlData := addressToXml(vIdAddress, vNameAddress);
		statusXmlData := statusCall(successcode(), 'Inserted')
		return;
	end; 
	else  begin 
		update addressTable
			set nameAddress = vNameAddress
		where
			idaddress = vIdAddress;
			statusXmlData := statusCall(successcode(), 'Updated')
			return;
    end;
    end if;
  end;
$$ language plpgsql VOLATILE;




